package com.tianji.aigc.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.tianji.aigc.agent.AbstractAgent;
import com.tianji.aigc.agent.Agent;
import com.tianji.aigc.enums.AgentTypeEnum;
import com.tianji.aigc.enums.ChatEventTypeEnum;
import com.tianji.aigc.service.ChatService;
import com.tianji.aigc.vo.ChatEventVO;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.Map;

@Service
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "tj.ai", name = "chat-type", havingValue = "ROUTE")
public class AgentServiceImpl implements ChatService {
    /**
     * 处理聊天请求，通过路由智能体分析用户意图并执行相应逻辑
     * @param question 用户提问内容
     * @param sessionId 会话ID
     * @return 返回聊天事件流，包含处理结果和结束事件
     */
    @Override
    public Flux<ChatEventVO> chat(String question, String sessionId) {
        //先通过路由智能体，分析用户意图，在执行后面的逻辑
        String result = findAgentByType(AgentTypeEnum.ROUTE).process(question, sessionId);
        //查找对应的路由体
        Agent agent = findAgentByType(AgentTypeEnum.agentNameOf(result));

        //如果找不到对应的处理智能体，则直接返回路由结果
        if (agent== null){
            ChatEventVO chatEventVO = ChatEventVO.builder()
                    .eventType(ChatEventTypeEnum.DATA.getValue())
                    .eventData(result)
                    .build();
            return Flux.just(chatEventVO, AbstractAgent.STOP_EVENT);

        }

        //使用找到的智能体处理流式聊天请求
        return agent.processStream(question, sessionId);
    }

    /**
     * 根据代理类型查找对应的Agent实例
     * @param agentTypeEnum 代理类型枚举，用于匹配对应的Agent实例
     * @return 返回匹配的Agent实例，如果未找到或参数为null则返回null
     */
    private Agent findAgentByType(AgentTypeEnum agentTypeEnum){
        if (agentTypeEnum == null){
            return null;
        }
        Map<String, Agent> beans = SpringUtil.getBeansOfType(Agent.class);
        //遍历所有的Agent Bean查找对应类型
        for (Agent agent : beans.values()) {
            if (agent.getAgentType() == agentTypeEnum){
                return agent;
            }
        }
        return null;
    }

    @Override
    public void stop(String sessionId) {
        findAgentByType(AgentTypeEnum.ROUTE).stop(sessionId);
    }
}
